<template>
  <commonDialog :model-value="modelValue" @close="cancel" @sure="addRoleResourceInfo" :title="title" size="50%">
    <el-scrollbar>
      <el-tree ref="treeRef" :data="resourcesList" style="height: 400px"
               node-key="id" :show-checkbox="true" highlight-current :check-strictly="checkStrictly"></el-tree>
    </el-scrollbar>
    <template #footer>
      <span>
        <el-button @click="cancel">关闭</el-button>
        <el-button type="primary" @click="addRoleResourceInfo">保存</el-button>
      </span>
    </template>
  </commonDialog>
</template>

<script>
import { post } from '@/utils/httpRequest'
import {
  addRoleResourceUrl,
  queryResourceByRoleIdUrl,
  selectAllResources
} from '@/api/api'
import { nextTick, onMounted, ref, toRefs } from 'vue'
import { propsConst } from '@/utils/propsConstant'
import { ElMessage } from 'element-plus'
import { joinList } from '@/utils/util'

export default {
  name: 'resource',
  setup (props, { emit }) {
    const { id } = toRefs(props)
    const treeRef = ref(null)
    // 选中的资源集合
    const checkedNodeKeys = ref([])
    const checkStrictly = ref(false)
    // 所有的资源集合
    const resourcesList = ref([])
    const addRoleResourceInfo = async () => {
      const data = {
        id: id.value,
        list: []
      }
      data.list = treeRef.value.getCheckedKeys().concat(treeRef.value.getHalfCheckedKeys())
      const result = await post(addRoleResourceUrl, data)
      if (result.code === 200) {
        ElMessage.success('编辑权限成功')
        cancel()
      }
    }
    const cancel = () => {
      emit('update:modelValue', false)
    }
    // 获取当前用户的资源
    const getUserResource = async () => {
      const result = await post(queryResourceByRoleIdUrl, { id: id.value })
      if (result.code === 200) {
        checkedNodeKeys.value = joinList(result.data, 'resourceId', '', false)
        checkStrictly.value = true
        await nextTick(() => {
          treeRef.value.setCheckedKeys(checkedNodeKeys.value)
          checkStrictly.value = false
        })
      }
    }
    // 获取所有资源列表
    const getAllResourceList = async () => {
      const result = await post(selectAllResources, {})
      if (result.code === 200) {
        resourcesList.value = result.data
      }
    }
    onMounted(async () => {
      await getAllResourceList()
      await getUserResource()
    })
    return {
      checkStrictly,
      treeRef,
      resourcesList,
      addRoleResourceInfo,
      cancel
    }
  },
  props: propsConst
}
</script>

<style scoped>

</style>
